package luit.mmt02.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import luit.mmt02.R;
import luit.mmt02.adapter.attach_adapter;
import luit.mmt02.doituong.attach;
import luit.mmt02.doituong.showToast;
import luit.mmt02.secutity.AESControl;
import luit.mmt02.secutity.DEScontrol;
import luit.mmt02.secutity.KeyManager;
import luit.mmt02.secutity.RSAControl;
import luit.mmt02.secutity.TripleDEScontrol;
import luit.mmt02.secutity.webserviceRequest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class attach_encryptActivity extends Activity
{
	final static String PATH_GET_KEY_DE = "/EncryptEmail/getkey_de/";
	final static String PUBLIC_KEY = "Public key ";
	final static String KEY_NGUOIGUI_NGUOINHAN = "KEY_NGUOIGUI_NGUOINHAN";
	final static String KEY_NGUOINHAN = "NGUOINHAN";
	final static String PATH_PUBLIC = "/EncryptEmail/keymail/";
	final static String KEY_ATTACH_ENCRYPT = "ATTACH_DA_MAHOA";
	final static String KEY_CHUOI_ATTACH_SEND = "chuoi_attach_send";
	ListView listview;
	List<attach>list;
	ArrayAdapter<attach>adapter;
	showToast st;
	TextView txthelp ;
	//
	String str_att;
	String tag = "attach_encrypt_activity";
	
	//
	String keyname; //loaikey ma hoa
	String str_loaimahoa; //loai ma hoa
	String output;
	String str_nguoigui_nguoinhan;
	String str_namekeyfile,str_pathkey,progress, progress2;
	String str_nguoinhan;
	boolean flag_getkey = false;
	KeyManager mykey;
	AESControl aes;
	DEScontrol des;
	TripleDEScontrol tdes;
	RSAControl rsa;
	webserviceRequest webservice;///
	
	List<Integer>list_idel; // list luu vi tri xoa
	List<attach>list_add; //list add ds sau khi ma hoa
	boolean flag_enc_publickey;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attach_encrypt);
		//
		Intent i_get = getIntent();
		str_att = i_get.getStringExtra(KEY_CHUOI_ATTACH_SEND);
		str_nguoigui_nguoinhan = i_get.getStringExtra(KEY_NGUOIGUI_NGUOINHAN);
		str_nguoinhan = i_get.getStringExtra(KEY_NGUOINHAN);
		Log.v(tag, "nhan dc chuoi att : " +str_att + " -- va chuoi nguoi gui-nhan :"+ str_nguoigui_nguoinhan);
		//
		mykey = new KeyManager();
		str_loaimahoa = "";
		//
		st = new showToast(this);
		listview = (ListView) findViewById(R.id.lv_attachencrypt);
		list = new ArrayList<attach>();
		txthelp = (TextView) findViewById(R.id.txt_att_encrypt_help);
		
		if(!str_att.equals(""))
		{
			String []arr_att = str_att.split(";");
			for(String str_1_att:arr_att)
			{
				list.add(new attach(str_1_att, true));
			}
		}
		adapter = new attach_adapter(this, list);
		listview.setAdapter(adapter);
	}
	
	public void img_onClick(View v)
	{
		ImageButton img = (ImageButton)v;
		switch (img.getId()) {
		case R.id.img_att_encrypt_backA:
			finish();
			break;
		case R.id.img_att_encrypt_menu:
			openOptionsMenu();
			break;

		default:
			break;
		}
	}
	
	public void btn_onClick(View v)
	{
		Button btn = (Button)v;
		switch (btn.getId()) {
		case R.id.btn_att_encrypt_OK:
			ok();
			break;
		case R.id.btn_att_encrypt_mahoa:
//			mahoa();
			encrypt_File_dialog();
			break;
		default:
			break;
		}
	}
	
	public void mahoa()
	{
		try
		{
			for(int i = list.size()-1; i >= 0; i --)
			{
				attach att = list.get(i);
				if(att.isCheck())
				{
					if(str_loaimahoa.equals("AES"))
					{
						Log.v(tag, "vao ma hoa aes");
						keyname = Environment.getExternalStorageDirectory().getAbsolutePath()
								+ PATH_PUBLIC +  "/keyaes.key";
						output = att.getStr_attach() + ".enc3";
						aes = new AESControl(mykey.getKeyAES(keyname));
						aes.EncFile(att.getStr_attach(), output);
						Log.v(tag, "ma hoa file aes thanh cong.." );
						//add vao attach
						list.remove(i);
						list.add(new attach(output, true));
						adapter.notifyDataSetChanged();
						txthelp.setText(getResources().getString(R.string.help_encrypt2));
					}
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi ma hoa" + e.toString());
		}
	}
	
	public void ok()
	{
		str_att = "";
		try {
			for(int i = 0 ; i < list.size(); i ++)
			{
				if(list.get(i).isCheck())
				{
					str_att += list.get(i).getStr_attach();
					str_att += ";";
				}
			}
			Log.v(tag, "truyen qua encrypt chuoi att  " +str_att);
			Intent intent = new Intent();
			intent.putExtra(KEY_ATTACH_ENCRYPT, str_att);
			setResult(RESULT_OK, intent);
			finish();
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "err OK" + e.toString());
		}
	}
	
	public void encrypt_File_dialog()
	{
		try 
		{
			List<String>list_item = new ArrayList<String>();
	 		list_item.add("AES");
	 		list_item.add("DES");
	 		list_item.add("3DES");
	 		int iit = str_nguoinhan.split(";").length;
	 		if(iit == 1) // neu chi co 1 ng nhan
	 		{
	 			list_item.add(PUBLIC_KEY);
	 		}
//	    	final CharSequence[] items  = {"AES", "DES", "3DES", PUBLIC_KEY };
	 		final CharSequence[] items = list_item.toArray(new CharSequence[list_item.size()]);
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	builder.setTitle(getResources().getString(R.string.ChonLoaiMaHoa));
	    	builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int item) {
//	    	        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
	    	        str_loaimahoa = items[item].toString();
	    	    }
	    	});
	    	
	    	builder.setPositiveButton("OK", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					Log.v(tag, "giai thuat duoc chon : " + str_loaimahoa);
					encryptFile_action();
				}
			});
	    	builder.setNegativeButton("Cancel", new OnClickListener() {
				
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					str_loaimahoa = "";
					Toast.makeText(getApplicationContext(), "huy ma hoa", Toast.LENGTH_SHORT).show();
				}
			});
	    	
	    	AlertDialog alert = builder.create();
	    	alert.show();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-encryptFiledialog", e.toString());
		}
	}
	
	public void encryptFile_action()
	{
		try 
		{
			if(str_loaimahoa.equals(""))
				{
					st.showmess(getResources().getString(R.string.ChonLoaiMaHoa));
				}
				else
				{
					
					flag_enc_publickey = false;
 					str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
 			 		Log.v("str_namekeyfile = ",  str_namekeyfile);////
 			 		File savedirsub = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC);
 			 		if(!savedirsub.isDirectory())
 			 		{
 							savedirsub.mkdirs();
 							Log.v(tag,"tao thu muc");
 			 		}
 			 		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+str_namekeyfile;
 			 		
 			 		//neu dung public key de ma hoa, doi duong dan
 			 		if(str_loaimahoa.equalsIgnoreCase(PUBLIC_KEY))
 			 		{
 			 			flag_enc_publickey = true;
 			 			Log.v("str_nguoinhan=",str_nguoinhan);////
 			 			if(str_nguoinhan.split(";").length==1)
 			 			{
 			 				str_nguoinhan=str_nguoinhan.replaceAll(";", "").trim();
 			 				File savedirsubPUB = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_GET_KEY_DE);
 		 			 		if(!savedirsubPUB.isDirectory())
 		 			 		{
 		 			 			savedirsubPUB.mkdirs();
 		 							Log.v(tag,"tao thu muc");
 		 			 		}
 			 				String path_key_pu_encrypt = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_GET_KEY_DE+str_nguoinhan+" keypu.key";
 			 				str_pathkey = path_key_pu_encrypt;
 			 				
 			 			}
 			 		}
 			 		Log.v(tag + "attach action	", str_pathkey );////
			 		File f = new File(str_pathkey);
				      if(!f.isFile())
				      {
				    	 flag_getkey = true;
				      	 progress = getResources().getString(R.string.getkey);
				      	 progress2 = getResources().getString(R.string.getkey_suc);
				      	 new sync_enc().execute("createkey");
				      }
				      else
				      {
				    	  flag_getkey = false;
				    	  progress = getResources().getString(R.string.enc_action);
				    	  progress2 = getResources().getString(R.string.enc_suc);
				    	  new sync_enc().execute("mahoa");
				      }
				}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-EncryptFile Action", e.toString());
		}
	}
	private class sync_enc extends AsyncTask<String, String, String>
 	{
 		ProgressDialog p = new ProgressDialog(attach_encryptActivity.this);
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			p.setMessage(progress);
			p.show();
		}
 		@Override
 		protected String doInBackground(String... params) {
 			// TODO Auto-generated method stub
 			if(flag_getkey)
 			{
 				create_key();
 			}
 			else
 				mahoa2();
 			return null;
 		}
 		@Override
 		protected void onPostExecute(String result) {
 			// TODO Auto-generated method stub
 			super.onPostExecute(result);
 			p.dismiss();
 			if(!flag_getkey)
// 				txt_encrypt.setText(str_mess_encrypt);
 			
 			st.showmess(progress2);
 			if(flag_getkey)
 			{
 				continue_dialog();
 			}
 			list_del_add();
 		}
 	}
 	public void continue_dialog()
 	{
 		try 
 		{
			AlertDialog.Builder builder = new Builder(this);
			builder.setMessage(getResources().getString(R.string.reg_suc_encrypt));
			String next = getResources().getString(R.string.Next);
			builder.setPositiveButton(next, new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					mahoa2();
//					txt_encrypt.setText(str_mess_encrypt);
				}
			});
			builder.setNegativeButton(getResources().getString(R.string.Cancel), new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			
			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-continue dialog", e.toString());
		}
 	}
 	
 	public void create_key()
 	{
 		try 
 	 	{
 			if(flag_enc_publickey) // xin key public
 	 		{
 	 			Log.v(tag, "file pulbic key de ma hoa CHUA CO , bat dau tao key");
				webservice  = new webserviceRequest(str_nguoigui_nguoinhan, "RSApu");
				webservice.getPuRSAKey_encrypt(str_nguoinhan);
				Log.v(tag, "xin key thanh cong");
 	 		}
 	 		else
 	 		{
 	 	//chua co key trong thu muc emailkey ==>goi ham gui request len server lay key ve roi luu tru;
		      	Log.i(tag, "chua co key trong thu muc emailkey ==> request key");
		      	Log.i("tag","truoc khi goi ham request web service voi nguoigui_nguoin="+str_nguoigui_nguoinhan+"||loaimahoa="+str_loaimahoa);
		      	webservice = new webserviceRequest(str_nguoigui_nguoinhan, str_loaimahoa);////
		      	Log.i("tag","truoc khi goi ham request web service voi nguoigui_nguoin="+str_nguoigui_nguoinhan+"||loaimahoa="+str_loaimahoa);
		      	webservice.getkeyStringEncrypt();////
		      	Log.i(tag, "Da tao xong key va luu xuong sdcard/EncrypEmail/keymail");
 	 		}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-createkey", "err create key" +e.toString());
		}
 	}
 	
 	public void mahoa2()
 	{
 		try 
 		{
 			list_idel = new ArrayList<Integer>();
 			list_add = new ArrayList<attach>();
 			for(int i = list.size()-1; i >= 0; i --)
			{
				attach att = list.get(i);
				if(att.isCheck())
				{
					if(str_loaimahoa.equals("AES"))
					{
						Log.v(tag, "vao ma hoa aes");
						output = att.getStr_attach() + ".enc3";
						aes = new AESControl(mykey.getKeyAES(str_pathkey));
						aes.EncFile(att.getStr_attach(), output);
						Log.v(tag, "ma hoa file aes thanh cong.." );
						
						//add vao attach
//						list.remove(i);
//						list.add(new attach(output, true));
//						adapter.notifyDataSetChanged();
//						txthelp.setText(getResources().getString(R.string.help_encrypt2));
					}
					if(str_loaimahoa.equals("DES"))
					{
						Log.v(tag + "-mahoa2", "vao ma hoa file voi des");
						output = att.getStr_attach() + ".enc1";
						des = new DEScontrol(mykey.getKeyDES(str_pathkey));
						des.encryptFile(att.getStr_attach(), output);
						Log.v(tag + "-mahoa2 ", "ma hoa file\thanh cong.." );
						//
//						list.remove(i);
//						list.add(new attach(output, true));
//						adapter.notifyDataSetChanged();
//						txthelp.setText(getResources().getString(R.string.help_encrypt2));
					}
					if(str_loaimahoa.equals("3DES"))
					{
						Log.v(tag + "-mahoa2", "vao ma hoa file voi tdes");
						output = att.getStr_attach() + ".enc2";
						tdes = new TripleDEScontrol(mykey.getKey3DES(str_pathkey));
						tdes.EncFile(att.getStr_attach(), output);
						Log.v(tag + "-mahoa2 ", "ma hoa file\thanh cong.." );
					}
					if(str_loaimahoa.equals(PUBLIC_KEY))
					{
						Log.v(tag + "-mahoa2", "vao ma hoa file voi public key");
						output = att.getStr_attach() + ".enc4";
						//
						//thuc hien ma hoa file voi key public o day
						rsa = new RSAControl(str_pathkey, false);
						//
						Log.v(tag + "-mahoa2 ", "ma hoa file\thanh cong.." );
					}
					Log.v(tag, "idel add - add add  ");
					list_idel.add(i);
					list_add.add(new attach(output, true));
					Log.v(tag, "idel add - add add 2 ");
//					st.showmess(getResources().getString(R.string.enc_suc));
//					list.remove(i);
//					list.add(new attach(output, true));
//					adapter.notifyDataSetChanged();
//					txthelp.setText(getResources().getString(R.string.help_encrypt2));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-mahoa2" , e.toString());
		}
 	}
 	
 	public void list_del_add()
 	{
 		try 
 		{
 			boolean flag = false;
			for(int i : list_idel)
			{
				list.remove(i);
				Log.v(tag+":listideladd:", "remove:" +i);
				flag = true;
			}
			
			for(attach atttemp : list_add)
			{
				list.add(atttemp);
				Log.v(tag+"::listideladd", "add them chu: "+atttemp.getStr_attach());
				flag = true;
			}
			
			if(flag)
			{
				Log.v(tag+"::listideladd", "adapter notify..");
				adapter.notifyDataSetChanged();
				Log.v(tag+"::listideladd", "adapter notify2..");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag+ "::listdeladd", e.toString());
		}
 	}
	
	
	
	
}
